package cc.sjfx.sharedoc.widget.adapter;

import java.util.List;
import java.util.Map;

import cn.bmob.v3.listener.UpdateListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.toast.MToast;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.BasicFragmentActivity;
import cc.sjfx.sharedoc.activity.examinfo.AlarmReceiver;
import cc.sjfx.sharedoc.activity.examinfo.EInfo;
import cc.sjfx.sharedoc.activity.user.UserLoginActivity;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.widget.view.myExpandableListView.MyExpandableListView;
import cc.sjfx.sharedoc.widget.view.myExpandableListView.MyExpandableListView.HeaderAdapter;

public class MyExpandableAdapter extends BaseExpandableListAdapter implements
		HeaderAdapter {
	// private String[][] childrenData;
	private Map<String, Map<String, EInfo>> map;
	private String[] groupData;
	private Context context;
	private MyExpandableListView listView;
	private LayoutInflater inflater;
	private int month;

	public MyExpandableAdapter(Map<String, Map<String, EInfo>> map,
			String[] groupData, Context context, int month,
			MyExpandableListView listView) {
		this.groupData = groupData;
		this.map = map;
		this.context = context;
		this.listView = listView;
		this.month = month;
		inflater = LayoutInflater.from(this.context);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return map.get(groupPosition + "").get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		View view = null;
		final ViewHolder holder;
		final EInfo info = map.get(groupPosition + "").get(childPosition + "");
		boolean remind = false;
		if (UserCache.isLogin) {
			remind = UserCache.user.getEidList().contains(
					new Integer(info.getEid()));
			MLog.i(UserCache.user.getEidList().size() + ":" + info.getEid()
					+ remind);
		} else {
			remind = false;
		}
		if (convertView != null) {
			view = convertView;
			holder = (ViewHolder) view.getTag();
		} else {
			holder = new ViewHolder();
			view = createChildrenView();
			holder.dateText = (TextView) view.findViewById(R.id.dateText);
			holder.dateText.setText(info.getDate());
			holder.examNameText = (TextView) view.findViewById(R.id.nameText);
			holder.remindBut = (Button) view.findViewById(R.id.remindBut);
			holder.remindText = (TextView) view.findViewById(R.id.remindText);
			view.setTag(holder);
		}
		long t = System.currentTimeMillis() / 1000;
		long time = info.getTime();
		holder.remindText.setVisibility(View.GONE);
		holder.remindBut.setVisibility(View.VISIBLE);
		if (time < t && time >= 0) {
			holder.remindBut.setText("已结束");
			holder.remindBut
					.setBackgroundResource(R.drawable.button_examinfo_overtime);
			holder.remindBut.setClickable(false);
		} else if (time >= 0) {
			if (remind) {
				holder.remindBut.setText("取消提醒");
				holder.remindBut.setClickable(true);
				holder.remindBut
						.setBackgroundResource(R.drawable.button_examinfo_ok);
			} else {
				holder.remindBut.setText("添加提醒");
				holder.remindBut.setClickable(true);
				holder.remindBut
						.setBackgroundResource(R.drawable.button_examinfo_remind);

			}
			holder.remindBut.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (!UserCache.isLogin) {
						((BasicFragmentActivity) context).startActivity(null,
								UserLoginActivity.class);
						return;
					}
					boolean remind;
					remind = UserCache.user.getEidList().contains(
							new Integer(info.getEid()));
					setRemind(info, holder.remindBut, remind, info.getEid());
				}
			});
		} else {
			holder.remindText.setVisibility(View.VISIBLE);
			holder.remindBut.setVisibility(View.GONE);
		}
		holder.dateText.setText(info.getDate());
		holder.examNameText.setText(info.getExamName());
		return view;
	}

	protected void setRemind(final EInfo info, final Button remindBut,
			final boolean remind, int i) {
		// TODO Auto-generated method stub
		List<Integer> list = UserCache.user.getEidList();
		if (remind) {
			list.remove(new Integer(i));
		} else {
			list.add(i);
		}
		User user = new User();
		user.setEidList(list);
		user.update(context, UserCache.user.getObjectId(),
				new UpdateListener() {

					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						if (remind) {
							Intent intent = new Intent(context,
									AlarmReceiver.class);
							intent.setAction("AlarmReceive");
							intent.setType(info.getEid() + "");
							intent.setData(Uri.EMPTY);
							intent.addCategory(info.getEid() + "");
							intent.setClass(context, AlarmReceiver.class);
							PendingIntent pendingIntent = PendingIntent
									.getBroadcast(context, 1, intent, 0);
							// alarmCount对应到你设定时的alarmCount,
							AlarmManager am = (AlarmManager) context
									.getSystemService(Context.ALARM_SERVICE);
							am.cancel(pendingIntent);
							MToast.show(context, "已取消");
							remindBut.setText("添加提醒");
							remindBut.setClickable(true);
							remindBut
									.setBackgroundResource(R.drawable.button_examinfo_remind);
						} else {
							Intent intent = new Intent(context,
									AlarmReceiver.class);
							intent.setAction("AlarmReceive");
							intent.setType(info.getEid() + "");
							intent.setData(Uri.EMPTY);
							intent.putExtra("examName", info.getExamName());
							intent.addCategory(info.getEid() + "");
							intent.setClass(context, AlarmReceiver.class);
							// 以上给intent设置的四个属性是用来区分你发给系统的闹钟请求的，当你想取消掉之前发的闹钟请求，这四个属性，必须严格相等，所以你需要一些比较独特的属性，比如服务器返回给你的json中某些特定字段。
							// 当然intent中也可以放一些你要传递的消息。
							PendingIntent pendingIntent = PendingIntent
									.getBroadcast(context, 1, intent, 0);
							// alarmCount是你需要记录的闹钟数量，必须保证你所发的alarmCount不能相同，最后一个参数填0就可以。
							AlarmManager am = (AlarmManager) context
									.getSystemService(Context.ALARM_SERVICE);
//							(info.getTime()-14400)*1000
							am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,
									pendingIntent);
							MToast.show(context, "已添加提醒");
							remindBut.setText("取消提醒");
							remindBut.setClickable(true);
							remindBut
									.setBackgroundResource(R.drawable.button_examinfo_ok);
						}
						notifyDataSetChanged();
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub

					}
				});
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return map.get(groupPosition + "").size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return groupData[groupPosition];
	}

	@Override
	public int getGroupCount() {
		return groupData.length;
	}

	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		View view = null;
		if (convertView != null) {
			view = convertView;
		} else {
			view = createGroupView();
		}

		ImageView iv = (ImageView) view.findViewById(R.id.groupIcon);
		if (isExpanded) {
			iv.setImageResource(R.drawable.btn_browser2);
		} else {
			iv.setImageResource(R.drawable.btn_browser);
		}

		TextView text = (TextView) view.findViewById(R.id.groupto);
		text.setText(groupData[groupPosition]);
		if (groupPosition < 13 - month) {
			view.setBackgroundColor(Color.rgb(254, 254, 254));
		} else {
			view.setBackgroundColor(Color.rgb(0xcb, 0xd3, 0xce));
		}
		return view;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	private View createChildrenView() {
		return inflater.inflate(R.layout.myexpandablelistliew_child, null);
	}

	private View createGroupView() {
		return inflater
				.inflate(R.layout.myexpandablelistliew_otherparent, null);
	}

	@Override
	public int getHeaderState(int groupPosition, int childPosition) {
		final int childCount = getChildrenCount(groupPosition);
		if (childPosition == childCount - 1) {
			return PINNED_HEADER_PUSHED_UP;
		} else if (childPosition == -1
				&& !listView.isGroupExpanded(groupPosition)) {
			return PINNED_HEADER_GONE;
		} else {
			return PINNED_HEADER_VISIBLE;
		}
	}

	@Override
	public void configureHeader(View header, int groupPosition,
			int childPosition, int alpha) {
		String groupData = this.groupData[groupPosition];
		((TextView) header.findViewById(R.id.groupto)).setText(groupData);

	}

	private SparseIntArray groupStatusMap = new SparseIntArray();

	@Override
	public void setGroupClickStatus(int groupPosition, int status) {
		groupStatusMap.put(groupPosition, status);
	}

	@Override
	public int getGroupClickStatus(int groupPosition) {
		if (groupStatusMap.keyAt(groupPosition) >= 0) {
			return groupStatusMap.get(groupPosition);
		} else {
			return 0;
		}
	}

	private class ViewHolder {
		public TextView dateText;
		public TextView examNameText;
		public Button remindBut;
		public TextView remindText;
	}
}
